package com.xingkeduo.pojo.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.table.PictureTable;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

public class PictureJson extends BaseJson {

	public static long createQueryForPicture(String json) throws Throwable {
		JsonNode root = validJson(json);
		if (root == null){
			throw new InputParamException(InputParamException.Type.INVALID, "参数格式");
		}
		return validId(root, YesNoEnum.YES);
	}

	public static PictureTable createTableForModifyPicture(String urlParam, PictureTable pictureTable) throws Throwable {
		JsonNode root = validJson(urlParam);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");
		pictureTable.setId(validId(root, YesNoEnum.YES));

		return pictureTable;
	}


	public static ObjectNode toJson(PictureTable pictureTable) {
		ObjectNode root = MAPPER.createObjectNode();

		if (pictureTable != null)
		{
			root.put("id", pictureTable.getId());
			root.put("code", pictureTable.getCode());
			root.put("ossId", pictureTable.getOssId());
            root.put("picDir", pictureTable.getPicDir());
            root.put("picType", pictureTable.getPicType());
			//处理时间
			String createdTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(pictureTable.getCreatedTime());
			root.put("createtime", createdTime);
		}
		return root;
	}

	public static ArrayNode toJson(List<PictureTable> pictureTableList) throws Throwable {
		ArrayNode root = MAPPER.createArrayNode();

		if(!CommonUtil.isEmpty(pictureTableList)){
			for (Iterator<PictureTable> iterator = pictureTableList.iterator(); iterator.hasNext();) {
				root.add(toJson(iterator.next()));
			}
		}

		return root;
	}
	public static ObjectNode toJsonPage(Page<PictureTable> page) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();
		if (page != null)
		{
			root.put("pageNo", page.getPageNo());
			root.put("pageSize", page.getPageSize());
			root.put("pageTotal", page.getPageTotal());
			root.put("recordTotal", page.getRecordTotal());
			root.put("dtoLists", toJson(page.getDtoList()));
		}
		return root;
	}

}
